package com.droidzxy.membership;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.huawei.agconnect.AGCRoutePolicy;
import com.huawei.agconnect.AGConnectInstance;
import com.huawei.agconnect.AGConnectOptionsBuilder;
import com.huawei.agconnect.auth.AGConnectAuth;
import com.huawei.agconnect.cloud.database.AGConnectCloudDB;
import com.huawei.agconnect.cloud.database.CloudDBZone;
import com.huawei.agconnect.cloud.database.CloudDBZoneConfig;
import com.huawei.agconnect.cloud.database.CloudDBZoneObjectList;
import com.huawei.agconnect.cloud.database.CloudDBZoneQuery;
import com.huawei.agconnect.cloud.database.CloudDBZoneSnapshot;
import com.huawei.agconnect.cloud.database.exceptions.AGConnectCloudDBException;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;

import java.util.ArrayList;
import java.util.Collections;

import model.memberInfo;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String TAG = MainActivity.class.getSimpleName();
    //初始化数据库
    AGConnectCloudDB mCloudDB;
    //初始化数据库配置
    CloudDBZoneConfig mConfig;
    //初始化存储区
    CloudDBZone mCloudDBZone;
    //初始化表格

    //云端数据对象List
    private ArrayList<MemberAdapter.MemberItem> mMemberList = new ArrayList<MemberAdapter.MemberItem>();

    private Button btnSignout;
    private RecyclerView rvMemberList;
    private MemberAdapter mMemberAdapter;

    private ImageView imgBack;
    private ImageView imgAdd;

    private int mCurDbIndex = 100000;

    public interface UiCallBack {
        void onDelete(memberInfo info);

        void onModify(memberInfo info);
    }

    private UiCallBack mUiCallBack = new UiCallBack() {
        @Override
        public void onDelete(memberInfo info) {
            AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).create();
            dialog.setCancelable(true);
            dialog.show();

            LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
            View v = inflater.inflate(R.layout.dialog_update, null);
            TextView txtTitle = v.findViewById(R.id.txt_dlg_title);
            TextView txtCardNum = v.findViewById(R.id.txt_dlg_cardnum);
            EditText edtName = v.findViewById(R.id.edt_dlg_name);
            EditText edtLevel = v.findViewById(R.id.edt_dlg_level);
            EditText edtPoints = v.findViewById(R.id.edt_dlg_points);

            txtTitle.setText("删除会员");
            txtCardNum.setText(info.getId().toString());
            edtName.setText(info.getName());
            edtLevel.setText(info.getLevel().toString());
            edtPoints.setText(info.getPoints().toString());

            edtName.setInputType(InputType.TYPE_NULL);
            edtLevel.setInputType(InputType.TYPE_NULL);
            edtPoints.setInputType(InputType.TYPE_NULL);

            Button btnOK = v.findViewById(R.id.btn_dlg_ok);
            btnOK.setOnClickListener(new View.OnClickListener(){

                @Override
                public void onClick(View view) {

                    if (mCloudDBZone == null) {
                        Log.w(TAG, "CloudDBZone is null, try re-open it");
                        return;
                    }

                    Task<Integer> deleteTask = mCloudDBZone.executeDelete(info);
                    deleteTask.addOnSuccessListener(new OnSuccessListener<Integer>() {
                        @Override
                        public void onSuccess(Integer integer) {
                            Toast.makeText(MainActivity.this, "删除成功！", Toast.LENGTH_SHORT).show();
                            updateData();
                            dialog.dismiss();
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(Exception e) {
                            Toast.makeText(MainActivity.this, "删除失败！", Toast.LENGTH_SHORT).show();
                        }
                    });


                }
            });
            Button btnCancel = v.findViewById(R.id.btn_dlg_cancel);
            btnCancel.setOnClickListener(new View.OnClickListener(){

                @Override
                public void onClick(View view) {
                    dialog.cancel();
                }
            });
            dialog.getWindow().setContentView(v);
            dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);


        }

        @Override
        public void onModify(memberInfo info) {


            AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).create();
            dialog.setCancelable(true);
            dialog.show();

            LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
            View v = inflater.inflate(R.layout.dialog_update, null);
            TextView txtTitle = v.findViewById(R.id.txt_dlg_title);
            TextView txtCardNum = v.findViewById(R.id.txt_dlg_cardnum);
            EditText edtName = v.findViewById(R.id.edt_dlg_name);
            EditText edtLevel = v.findViewById(R.id.edt_dlg_level);
            EditText edtPoints = v.findViewById(R.id.edt_dlg_points);

            txtTitle.setText("修改会员");
            txtCardNum.setText(info.getId().toString());
            edtName.setText(info.getName());
            edtLevel.setText(info.getLevel().toString());
            edtPoints.setText(info.getPoints().toString());

            Button btnOK = v.findViewById(R.id.btn_dlg_ok);
            btnOK.setOnClickListener(new View.OnClickListener(){

                @Override
                public void onClick(View view) {


                    boolean formatOK = true;
                    String msg = "";
                    if(edtName.getText().length() == 0) {
                        formatOK = false;
                        msg = "用户名不能为空";
                    } else if(edtLevel.getText().length() == 0) {
                        formatOK = false;
                        msg = "等级不能为空";
                    } else if(edtPoints.getText().length() == 0) {
                        formatOK = false;
                        msg = "积分不能为空";
                    }

                    if(formatOK == false) {
                        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
                    } else {
                        info.setId(Integer.parseInt(txtCardNum.getText().toString()));
                        info.setName(edtName.getText().toString());
                        info.setLevel(Integer.parseInt(edtLevel.getText().toString()));
                        info.setPoints(Integer.parseInt(edtPoints.getText().toString()));

                        Task<Integer> upsertTask = mCloudDBZone.executeUpsert(info);
                        upsertTask.addOnSuccessListener(new OnSuccessListener<Integer>() {
                            @Override
                            public void onSuccess(Integer cloudDBZoneResult) {
                                Toast.makeText(MainActivity.this, "修改成功！", Toast.LENGTH_SHORT).show();

                                updateData();
                                dialog.dismiss();
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(Exception e) {
                                Toast.makeText(MainActivity.this, "修改失败！", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            });
            Button btnCancel = v.findViewById(R.id.btn_dlg_cancel);
            btnCancel.setOnClickListener(new View.OnClickListener(){

                @Override
                public void onClick(View view) {
                    dialog.cancel();
                }
            });
            dialog.getWindow().setContentView(v);
            dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);







        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.statuscolor));
        }

        rvMemberList = findViewById(R.id.rv_list);



        imgBack = findViewById(R.id.img_back);
        imgBack.setOnClickListener(this);
        imgAdd = findViewById(R.id.img_add);
        imgAdd.setOnClickListener(this);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                openAndQueryCloudDB();

                mMemberAdapter = new MemberAdapter(mMemberList, mUiCallBack);
                rvMemberList.setLayoutManager(new LinearLayoutManager(MainActivity.this));
                rvMemberList.setAdapter(mMemberAdapter);
            }
        }, 500);

    }

    private void openAndQueryCloudDB() {
        //初始化云数据库
//        AGConnectCloudDB.initialize(getApplicationContext());
        AGConnectInstance instance = AGConnectInstance.buildInstance(new AGConnectOptionsBuilder().setRoutePolicy(AGCRoutePolicy.CHINA).build(getApplicationContext()));
//        mCloudDB = AGConnectCloudDB.getInstance(instance, AGConnectAuth.getInstance(instance));
        mCloudDB = AGConnectCloudDB.getInstance();
        Log.i(TAG,"The cloudDB is" + mCloudDB);
        try {
            mCloudDB.createObjectType(model.ObjectTypeInfoHelper.getObjectTypeInfo());
            mConfig = new CloudDBZoneConfig("memberInfoZone",
                    CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
                    CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
            mConfig.setPersistenceEnabled(true);
            Task<CloudDBZone> openDBZoneTask = mCloudDB.openCloudDBZone2(mConfig, true);
            openDBZoneTask.addOnSuccessListener(new OnSuccessListener<CloudDBZone>() {
                @Override
                public void onSuccess(CloudDBZone cloudDBZone) {
                    Log.i("open clouddbzone", "open cloudDBZone success");
                    mCloudDBZone = cloudDBZone;
                    updateData();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(Exception e) {
                    Log.w("open clouddbzone", "open cloudDBZone failed for " + e.getMessage());
                }
            });
        } catch (AGConnectCloudDBException e) {
            Toast.makeText(MainActivity.this, "initialize CloudDB failed" + e, Toast.LENGTH_LONG).show();
        }
    }

    private void updateData() {
        Log.d(TAG, "zzz, bindData was called.");

        CloudDBZoneQuery<memberInfo> query = CloudDBZoneQuery.where(memberInfo.class);
        queryMemberInfo(query);
    }

    private void queryMemberInfo(CloudDBZoneQuery<memberInfo> query) {
        if (mCloudDBZone == null) {
            Log.w(TAG, "CloudDBZone is null, try re-open it");
        }

        Task<CloudDBZoneSnapshot<memberInfo>> queryTask = mCloudDBZone.executeQuery(query,
                CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
        queryTask.addOnSuccessListener(new OnSuccessListener<CloudDBZoneSnapshot<memberInfo>>() {
            @Override
            public void onSuccess(CloudDBZoneSnapshot<memberInfo> snapshot) {
                try {
                    processQueryResult(snapshot);
                } catch (AGConnectCloudDBException e) {
                    Log.e(TAG, "onfailed: "+e.getErrMsg() );
                }
                Log.i(TAG, "onSuccess: query result success");
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Log.i(TAG, "onSuccess: query result failed," + e.toString());
            }
        });

    }


    private void processQueryResult(CloudDBZoneSnapshot<memberInfo> snapshot) throws AGConnectCloudDBException {
        CloudDBZoneObjectList<memberInfo> memberInfoCursor = snapshot.getSnapshotObjects();

        try {
            int index = 1;
            mMemberList.clear();
            while (memberInfoCursor.hasNext()) {
                memberInfo info = memberInfoCursor.next();
                mMemberList.add(new MemberAdapter.MemberItem(info.getId(),info.getName(),info.getLevel(),info.getPoints()));

            }
        } catch (AGConnectCloudDBException e) {
            Log.w(TAG, "processQueryResult: " + e.getMessage());
        } finally {
            snapshot.release();
//            mCloudDB.closeCloudDBZone(mCloudDBZone);

            Collections.sort(mMemberList);

            if(mMemberList.size() > 0) {
                mCurDbIndex = mMemberList.get(mMemberList.size() - 1).id;
            }

            mMemberAdapter.notifyDataSetChanged();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();

        try {
            mCloudDB.closeCloudDBZone(mCloudDBZone);
        } catch (AGConnectCloudDBException e) {
            e.printStackTrace();
        }

        if (AGConnectAuth.getInstance().getCurrentUser() != null) {
            // signOut
            AGConnectAuth.getInstance().signOut();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                onBackPressed();
                break;
            case R.id.img_add:
                showAddDialog();
                break;
        }
    }
    private void showAddDialog() {

        AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(true);
        dialog.show();

        LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
        View v = inflater.inflate(R.layout.dialog_update, null);
        TextView txtTitle = v.findViewById(R.id.txt_dlg_title);

        TextView txtCardNum = v.findViewById(R.id.txt_dlg_cardnum);
        EditText edtName = v.findViewById(R.id.edt_dlg_name);
        EditText edtLevel = v.findViewById(R.id.edt_dlg_level);
        EditText edtPoints = v.findViewById(R.id.edt_dlg_points);

        txtTitle.setText("增加会员");
        txtCardNum.setText(String.valueOf(mCurDbIndex + 1));



        Button btnOK = v.findViewById(R.id.btn_dlg_ok);
        btnOK.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {

                boolean formatOK = true;
                String msg = "";
                if(edtName.getText().length() == 0) {
                    formatOK = false;
                    msg = "用户名不能为空";
                } else if(edtLevel.getText().length() == 0) {
                    formatOK = false;
                    msg = "等级不能为空";
                } else if(edtPoints.getText().length() == 0) {
                    formatOK = false;
                    msg = "积分不能为空";
                }

                if(formatOK == false) {
                    Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
                } else {

                    if (mCloudDBZone == null) {
                        Log.w(TAG, "CloudDBZone is null, try re-open it");
                        return;
                    }
                    memberInfo info = new memberInfo();
                    info.setId(Integer.parseInt(txtCardNum.getText().toString()));
                    info.setName(edtName.getText().toString());
                    info.setLevel(Integer.parseInt(edtLevel.getText().toString()));
                    info.setPoints(Integer.parseInt(edtPoints.getText().toString()));

                    Task<Integer> upsertTask = mCloudDBZone.executeUpsert(info);
                    upsertTask.addOnSuccessListener(new OnSuccessListener<Integer>() {
                        @Override
                        public void onSuccess(Integer cloudDBZoneResult) {
                            Log.i(TAG, "Upsert " + cloudDBZoneResult + " records");
                            Toast.makeText(MainActivity.this, "添加成功！", Toast.LENGTH_SHORT).show();

                            updateData();

                            dialog.dismiss();
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(Exception e) {
                            Log.e(TAG, "zzz, failed add," + e.toString());
                        }
                    });


                }







            }
        });
        Button btnCancel = v.findViewById(R.id.btn_dlg_cancel);
        btnCancel.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                dialog.cancel();
            }
        });
        dialog.getWindow().setContentView(v);

        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

    }


}

